package com.gee.spring.boot.starter.opengemini.core.query.segment;


import com.gee.spring.boot.starter.opengemini.core.domain.ColumnInfo;
import com.gee.spring.boot.starter.opengemini.core.domain.SelectFunc;

import java.util.List;
import java.util.stream.Collectors;

import static com.gee.spring.boot.starter.opengemini.core.constant.StrConstant.*;
import static com.gee.spring.boot.starter.opengemini.core.enums.SqlKeyword.AS;


/**
 * @author gepengjun
 * @since 2024/4/28 8:39
 */
public class SelectSegment implements ISqlSegment{

    private ColumnInfo columnInfo;

    private SelectFunc selectFunc;

    public SelectSegment(ColumnInfo columnInfo, SelectFunc selectFunc) {
        this.columnInfo = columnInfo;
        this.selectFunc = selectFunc;
    }

    public ColumnInfo getColumnInfo() {
        return columnInfo;
    }

    public void setColumnInfo(ColumnInfo columnInfo) {
        this.columnInfo = columnInfo;
    }

    public SelectFunc getSelectFunc() {
        return selectFunc;
    }

    public void setSelectFunc(SelectFunc selectFunc) {
        this.selectFunc = selectFunc;
    }

    @Override
    public String getSqlSegment() {
        StringBuilder sqlSegment = new StringBuilder();
        if (selectFunc != null){
            sqlSegment.append(selectFunc.getKeyWork()).append(LEFT_BRACKET);
        }
        String column = columnInfo.getColumn();
        sqlSegment.append(column);
        if (selectFunc != null){
            List<Object> paramList = selectFunc.getParamList();
            if (paramList != null && paramList.size() > 0){
                sqlSegment.append(COMMA).append(paramList.stream()
                        .map(param -> {

                            if (param instanceof String){
                                return SINGLE_QUOTE + param + SINGLE_QUOTE;
                            }else {
                                return param.toString();
                            }
                        })
                        .collect(Collectors.joining(COMMA))
                );
            }
            sqlSegment.append(RIGHT_BRACKET).append(SPACE).append(AS.getKeyword()).append(SPACE);
            if ("".equals(columnInfo.getFuncAlias())){
                sqlSegment.append(column);
            }else {
                sqlSegment.append(columnInfo.getFuncAlias());
            }
        }

        return sqlSegment.toString();
    }
}
